<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router';
import { useUserStore } from '@/stores/user';

import { getCurrentClientTime } from '@/utils';
import { turntable } from '@/utils/adConfig.ts'

import { uploadViewAdType } from '@/api/ad'
import { fetchRewardsDetails } from '@/api/game'

import BiNavBar from '@/components/bi-navbar/index.vue'
import Points from '@/components/bi-header/components/points.vue';
import BiPopup from '@/components/bi-popup/index.vue'
import TurnTableGame from './components/turntableGame/index.vue'
import Ad from '@/components/ad/index.vue'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

const userInfo = ref(userStore.info)
userStore.$subscribe((_mutation, state) => {
    userInfo.value = state.info
})

const notLotteryCount = computed(() => {
    return userInfo.value.lotteryNums == userInfo.value.lotteryTotalNums
})

const hideReward = ref(false)

const handleWatchRewardAd = () => {
    closeRewardsPopup()
    try {
        android.showLotteryRewardAd()
    } catch (error) {
        console.log(error)
    }
}

onMounted(() => {
    window.watchLotteryRewardAd = (successful: boolean) => {
        if (successful) {
            handleGetRewardsDetails()
            handleUploadAdViewType()
        }
        console.log(successful)
    }
})

const handleGetRewardsDetails = async () => {
    try {
        const res = await fetchRewardsDetails({
            device: userStore.device,
            lotteryType: 1
        })
        userStore.handleGetUserInfo()
        rewards.value = res.data.data
        turnTableGame.value.startLottery()
    } catch (error) {
        throw new Error(error as string)
    }
}

const handleUploadAdViewType = async () => {
    try {
        await uploadViewAdType({ device: userStore.device, adType: 3, viewingTime: getCurrentClientTime() })
        console.log('Upload Successful')
    } catch (error: any) {
        throw new Error(error)
    }
}

const showRewardsPopup = ref(false)
const openRewardsPopup = () => {
    showRewardsPopup.value = true
}
const closeRewardsPopup = () => {
    showRewardsPopup.value = false
}
const handleActionGameFn = () => {
    if (notLotteryCount.value) {
        hideReward.value = true
        openRewardsPopup()
    } else {
        handleWatchRewardAd()
    }
}
const popupTypeForHideReward = computed(() => {
    return hideReward.value ? 'task' : 'normal'
})
const rewardsPopupBtnText = computed(() => {
    return notLotteryCount.value ? 'Get More' : 'Play Again'
})
const handleRewardsPopupFn = () => {
    const fn = notLotteryCount.value ? handleGetMoreRewards : handleWatchRewardAd
    fn()
}
const turnTableGame = ref<any>() // turnTableGame 组件
const initTurntable = () => {
    turnTableGame.value.initTurntable()
}
const rewardsPopupTips = computed(() => {
    const hasLotteryCount = userInfo.value.turntableNums < userInfo.value.turntableTotalNums
    return hasLotteryCount ? `Enter the "Easter Egg" to get more rewards!` : 'Watch AD to get more rewards!'
})
interface Rewards {
    winFlag: boolean // true: 获得圣杯; false: 获取火焰
    chailce: number, // 获得的圣杯数
    points: number // 获得的火焰数
}
const rewards = ref({} as Rewards)
const rewardsPopupIcon = computed(() => {
    return rewards.value.winFlag ? 'trophy' : 'flame'
})
const rewardsPopupNum = computed(() => {
    return rewards.value.winFlag ? rewards.value.chailce : rewards.value.points
})

const handleGetMoreRewards = () => {
    const hasLotteryCount = userInfo.value.turntableNums < userInfo.value.turntableTotalNums
    if (hasLotteryCount) {
        router.push({
            path: '/egg',
            query: {
                playAd: 1
            }
        })
    } else {
        android.watchRewardAd(50)
    }
}
onMounted(() => {
    if (route.query.playAd && !notLotteryCount) {
        handleWatchRewardAd()
    }
})

</script>

<template>
    <BiNavBar @click-left="router.back" background-color="transparent" arrow-color="#ffffff" left-text="God's Gift"
        left-text-size="24px" arrow-size="4.5vmin">
        <template #right>
            <Points :point="userInfo.totalPoints" style="margin-right: 2vmin;" />
        </template>
    </BiNavBar>

    <img class="game-normal-bg" src="@/assets/imgs/bg.png" alt="">

    <main class="main">
        <TurnTableGame ref="turnTableGame" @end="openRewardsPopup" />
        <div class="truntable-btn" @click="handleActionGameFn">
            <span class="text">Play ({{ userInfo.lotteryNums }}/{{ userInfo.lotteryTotalNums }})</span>
        </div>
    </main>

    <Ad :id="turntable.id" ad-type="adsense" style="margin-top: 4vmin;" />

    <!-- 转盘奖励弹窗 -->
    <BiPopup v-model:show="showRewardsPopup" :type="popupTypeForHideReward" :button-text="rewardsPopupBtnText"
        @click="handleRewardsPopupFn" @close="initTurntable" :rewards-type="rewardsPopupIcon"
        :rewards-num="rewardsPopupNum" :tips="rewardsPopupTips" :display-tips="notLotteryCount">
        <span v-if="hideReward" class="red-text" style="width: 59vmin;font-weight: bold;text-align: center;">{{
            rewardsPopupTips }}</span>
    </BiPopup>

</template>

<style scoped lang="scss">
@import url(./turntable.scss);
</style>